package com.scraper.articles.web.dao.impl;

import com.scraper.articles.web.dao.ArticleDao;
import com.scraper.articles.web.model.Article;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class ArticleDaoImpl extends BaseDao implements ArticleDao {

    @Override
    public void saveArticleList(List<Article> articles) {
        for (Article article : articles) {
            getSession().merge(article);
        }
    }

    @Override
    public boolean isArticleProcessed(String url) {
        Query query = getSession().createSQLQuery(
                "select * from article a where a.Url = :url")
                .addEntity(Article.class)
                .setParameter("url", url);
        List result = query.list();
        return !result.isEmpty();
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Article> listArticles() {
        return getSession().createCriteria(Article.class).list();
    }

    @Override
    public Article getArticle(Long id) {
        return (Article) getSession().get(Article.class, id);
    }

    @Override
    public List<Article> listArticles(Long requestId) {
        Query query = getSession().createSQLQuery(
                "select * from article a where a.RequestId = :requestId")
                .addEntity(Article.class)
                .setParameter("requestId", requestId);
        return query.list();
    }

    @Override
    public void deleteArticle(Long id) {
        Article article = getArticle(id);

        if (article != null) {
            getSession().delete(article);
        }
    }
}
